﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using KPIS.GERP.Models;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.SYS;
using WebMatrix.WebData;

namespace KPIS.GERP.WEB.GAMS.Class.MemberShip
{
    public class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            Database.SetInitializer<GERPContext>(null);

            using (var context = new GERPContext())
            {
                Exception databaseExistTestException = GetExceptionDatabaseExist(context);
                if (databaseExistTestException != null)
                {
                    throw databaseExistTestException;
                }

                if (!context.Database.Exists())
                {
                    // Create the SimpleMembership database without Entity Framework migration schema
                    ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                }

                WebSecurity.InitializeDatabaseConnection("GERPContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);

                InitialAdministrator(context);
            }
        }

        private void InitialAdministrator(GERPContext context)
        {
            CreateRoleIfNotExist("Admin"); 
            CreateRoleIfNotExist("Employee");

            foreach(var u in context.Users)
            {
                CreateUserIfNotExist(u.Code, u.Password);
                AddUserToRole(u.Code, u.IsAdmin ? "Admin" : "Employee");
            }

            context.SaveChanges();
        }

        private void CreateRoleIfNotExist(string roleName)
        {
            var roles = (SimpleRoleProvider)System.Web.Security.Roles.Provider;

            if (!roles.RoleExists(roleName))
            {
                roles.CreateRole(roleName);
            }
        }

        private void CreateUserIfNotExist(string userName, string password )
        {
            var membership = (SimpleMembershipProvider)System.Web.Security.Membership.Provider;
            if (membership.GetUser(userName, false) == null)
            {
                var resultSomething = membership.CreateUserAndAccount(userName, password);
                Logger.Log("membership not found user, create user and account : [" + resultSomething + "]");
            }
        }

        private void AddUserToRole(string userName, string roleName)
        {
            var roles = (SimpleRoleProvider)System.Web.Security.Roles.Provider;

            if (!roles.GetRolesForUser(userName).Any(r => CompareUtility.IsStringsEqual(r, roleName)))
                roles.AddUsersToRoles(new[] { userName }, new[] { roleName });
        }

        private Exception GetExceptionDatabaseExist(GERPContext context)
        {
            try
            {
                context.Database.Exists();
                return null;
            } catch(Exception ex)
            {
                return ex;
            }
        }
    }

}